import random


from django import http
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection
from libs.captcha.captcha import captcha

class SMSCodeView(View):
    def get(self,request, mobile):
        image_code = request.GET.get('image_code')
        uuid = request.GET.get('image_code_id')
        image_client = get_redis_connection('verify_image_code')
        redis_image_code = image_client.get('img_%s' % uuid)
        if not redis_image_code:
            return http.JsonResponse({"code": "4001", "errmsg": "图形验证码失效了"})
        image_client.delete('img_%s' % uuid)
        if image_code.lower() != redis_image_code.decode().lower():
            return http.JsonResponse({'code': "4001", 'errmsg': '输入图形验证码有误'})
        sms_code = "%06d" % random.randint(0,999999)
        print('当前验证码为', sms_code)
        redis_sms_client = get_redis_connection('sms_code')
        send_flag = redis_sms_client.get('send_flag_%s' % mobile)
        if send_flag:
            return http.JsonResponse({'code': "4002", 'errmsg': '发送短信过于频繁'})
        p1 = redis_sms_client.pipeline()
        p1.setex('sms_%s' % mobile, 300, sms_code)
        p1.setex('send_flag_%s' % mobile, 60, 1)
        p1.execute()
        print('------------------------------------------')
        print('当前验证码为',sms_code)
        print('------------------------------------------')

        return http.JsonResponse({'code': '0', 'errmsg': '发送短信成功'})









class ImageCodeView(View):
    """图形验证码"""

    def get(self, request, uuid):
        """
        # :param request: 请求对象
        # :param uuid: 唯一标识图形验证码所属于的用户
        # :return: image/jpg
        # """
        from libs.captcha.captcha import captcha
        text, image_code = captcha.generate_captcha()

        # 4.保存到redis中 为 后面 发送短信验证码做准备
        image_client = get_redis_connection('verify_image_code')
        # image_client.setex('img_%s' % uuid, 300, text)
        image_client.setex('img_%s' % uuid, 300, text)

        # 5.返回响应对象--->图片二进制流
        return http.HttpResponse(image_code, content_type='image/jpg')
